<template>
  <section>
    <!--工具条-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true" :model="filters">
        <el-form-item>
          <el-input v-model="filters.keyword" placeholder="请输入关键字"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" v-on:click="search">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleAdd">新增</el-button>
        </el-form-item>
      </el-form>
    </el-col>

    <!--列表-->
    <el-table :data="departments" highlight-current-row v-loading="listLoading"
              @selection-change="selsChange" style="width: 100%;">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column type="index" width="60">
      </el-table-column>
      <el-table-column prop="sn" label="编号" width="180" sortable>
      </el-table-column>
      <el-table-column prop="name" label="名称" width="220" sortable>
      </el-table-column>
      <el-table-column prop="state" label="状态" width="100" sortable>
        <template scope="scope">
          <span v-if="scope.row.state == 0" style="color: green">正常</span>
          <span v-else-if="scope.row.state == -1"style="color: red">禁用</span>
          <span v-else style="color: red">未知</span>
        </template>
      </el-table-column>
      <el-table-column prop="employee.username" label="管理员" width="180" sortable>
      </el-table-column>
      <el-table-column prop="department.name" label="上级部门" sortable>
      </el-table-column>
      <el-table-column label="操作" width="150">
        <template scope="scope">
          <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--工具条-->
    <el-col :span="24" class="toolbar">
      <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
      <el-pagination layout="prev, pager, next"
                     @current-change="handleCurrentChange"
                     :page-size="pageSize"
                     :total="total"
                     :current-page="currentPage"
                     style="float:right;">
      </el-pagination>
    </el-col>

    <!--编辑界面
    :visible.sync 控制窗体是否显示
    :rules=" 绑定表单的校验规则
     prop=" 绑定模型层的属性校验规则
     ref="editForm"  给当前表单去一个引用的别名
    -->
    <el-dialog :title="title" :visible.sync="editFormVisible" :close-on-click-modal="false">
      <el-form :model="editForm" label-width="80px" :rules="editFormRules" ref="editForm">
        <el-form-item label="名称" prop="name">
          <el-input v-model="editForm.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="编号" prop="sn">
          <el-input v-model="editForm.sn" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="editForm.state">
            <el-radio class="radio" :label="0">正常</el-radio>
            <el-radio class="radio" :label="-1">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="管理员">
          <!--<el-input auto-complete="off" v-model="editForm.employee"></el-input>-->
          <el-select v-model="editForm.employee" clearable value-key="id" placeholder="请选择">
            <!--
                   :key=  标明选项的唯一键
                   :label    下拉列表选中之后，显示在选择框中的值
                   :value 选中之后需要绑定给模型层的值
                   value-key="id" 作为绑定值为对象的时候必填
             -->
            <el-option
                v-for="item in employees"
                :key="item.id"
                :label="item.username"
                :value="item">
              <span style="float: left">{{ item.username }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.phone }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="上级部门">
          <!--<el-input auto-complete="off" v-model="editForm.department"></el-input>-->
          <el-cascader v-model="editForm.department"
                       :options="deptTree"
                       :props="{
                checkStrictly: true,
                value:'id',
                label:'name'
              }"
                       clearable></el-cascader>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="editFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="editSubmit" :loading="editLoading">提交</el-button>
      </div>
    </el-dialog>

  </section>
</template>

<script>
import util from '../../common/js/util'
//import NProgress from 'nprogress'
import { getDepartmentListPage, removeDepartment, batchRemoveDepartment, editDepartment, addDepartment } from '../../api/api';

export default {
  data() {
    return {
      title:"",
      filters: {
        keyword: ''
      },
      departments: [],
      employees:[],
      deptTree:[],
      total: 0,
      currentPage: 1,
      pageSize:10,
      listLoading: false,
      sels: [],//当前页 列表选的所有中行

      editFormVisible: false,//编辑界面是否显示
      editLoading: false,
      editFormRules: {//表单校验规则
        name: [//校验name属性
          { required: true, message: '请输入姓名', trigger: 'blur' }
        ],
        sn: [//sn
          { required: true, message: '请输入编号', trigger: 'blur' }
        ]
      },
      //编辑界面数据
      editForm: {
        id: null,
        name: '',
        sn: '',
        dirPath:'',
        state: 0,
        employee: null,
        department: null
      },

    }
  },
  methods: {
    search(){//高级查询按钮
      // 定位到第一页
      this.currentPage = 1;
      //调用查询刷新页面
      this.getDepartments();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getDepartments();
    },
    //获取部门列表
    getDepartments() {
      //请求参数
      let para = {
        currentPage: this.currentPage,
        pageSize: this.pageSize,
        keyword: this.filters.keyword//关键字查询
      };
      this.listLoading = true;//开启忙等
      //NProgress.start();
      this.$http.post("/dept",para)
          .then(result=>{
              this.listLoading = false;//关闭忙等框
              result = result.data;//PageList
              this.departments = result.rows;
              this.total = result.total;
          })
          .catch(result=>{
            console.log(result);
          })
      /*getDepartmentListPage(para).then((res) => {
        this.total = res.data.total;
        this.departments = res.data.departments;
        this.listLoading = false;
        //NProgress.done();
      });*/
    },
    //删除
    handleDel: function (index, row) {
      this.$confirm('确认删除该记录吗?', '温馨提示', {
        type: 'warning'
      }).then(() => {// 确定按钮
        this.listLoading = true;//开启忙等框
        this.$http.delete("/dept/"+row.id)//http://localhost:8080/dept/1
            .then(result=>{
              this.listLoading = false;//关闭忙等框
              result = result.data;
              if(result.success){//后端删除成功
                this.$message({
                  message: result.message,
                  type: 'success'
                });
              }else{//后端删除失败
                this.$message({
                  message: result.message,
                  type: 'error'
                });
              }
              this.currentPage = 1;
              this.getDepartments();//重新刷新页面
            })
            .catch(result=>{//调用后端调用不同
              this.$message({
                message: '系统繁忙，稍后重试',
                type: 'error'
              });
            })
      }).catch(() => {//取消按钮

      });
    },
    //显示编辑界面
    handleEdit: function (index, row) {
      this.getDeptTree();
      this.editFormVisible = true;//控制显示弹出框
      this.title = "编辑";
      // Object.assign({}, row) 克隆
      this.editForm = Object.assign({}, row);//渲染表单
      //将dirPath整成数组   "/27/28/29"
      if(this.editForm.dirPath){//如果不为空
        let arry = this.editForm.dirPath.split("/");// ["","27","28","29"]
        let dirPath = [];
        for(let i=1;i<=arry.length-2;i++){
          dirPath.push(parseInt(arry[i]));
        }
        console.log(dirPath);
        this.editForm.department = dirPath;
      }
    },
    //显示新增界面
    handleAdd: function () {
      this.getDeptTree();
      this.editFormVisible = true;//控制显示弹出框
      this.title = "新增";
      this.editForm = {// 表单重置
        id: null,
        name: '',
        sn: '',
        dirPath:'',
        state: 0,
        employee: null,
        department: null
      };

      this.$refs.editForm.resetFields();//重置表单校验
    },
    //新增和编辑提交按钮
    editSubmit: function () {
      //this.$refs.editForm.validate 找到editForm表单，主动开启校验  validate
      this.$refs.editForm.validate((valid) => {
        if (valid) {//校验通过
          this.$confirm('确认提交吗？', '温馨提示', {}).then(() => {
            this.editLoading = true;//提交按钮忙等 防止重复点击
            let para = Object.assign({}, this.editForm);
            //调整后端需要的数据格式  下午这里要搞事
            if(para.department){//有值  [2,7]-->{id:7}
              //将数组格式转换成对象
              para.department = {"id":para.department[para.department.length-1]}
            }
            this.$http.put("/dept",para)
                .then(result=>{
                  this.$refs['editForm'].resetFields();//重置表单校验
                  this.editLoading = false;//关闭按钮忙等
                  this.editFormVisible = false;//关闭弹出框
                  result = result.data;
                  if(result.success){//后端删除成功
                    this.$message({
                      message: result.message,
                      type: 'success'
                    });
                  }else{//后端删除失败
                    this.$message({
                      message: result.message,
                      type: 'error'
                    });
                  }
                  this.currentPage = 1;
                  this.getDepartments();//重新刷新页面
                })
                .catch(result=>{//调用后端调用不同
                  this.editLoading = false;//关闭按钮忙等
                  this.$message({
                    message: '系统繁忙，稍后重试',
                    type: 'error'
                  });
                  this.$refs['editForm'].resetFields();//重置表单校验
                })
          });
        }
      });
    },
    selsChange: function (sels) {//每次点击复选框的时候触发函数
      this.sels = sels;
    },
    //批量删除
    batchRemove: function () {
      //this.sels 当前选中的所有行的数据
      var ids = this.sels.map(item => item.id);// [1,2,3]  注意：去掉.toString()
      this.$confirm('确认删除选中记录吗？', '温馨提示', {
        type: 'warning'
      }).then(() => {//确定要删除
        this.listLoading = true;
        //NProgress.start();
        /*let para = { ids: ids };*/
        this.$http.patch("/dept",ids)
            .then(result=>{
              this.listLoading = false;//关闭忙等框
              result = result.data;
              if(result.success){//后端删除成功
                this.$message({
                  message: result.message,
                  type: 'success'
                });
              }else{//后端删除失败
                this.$message({
                  message: result.message,
                  type: 'error'
                });
              }
              this.currentPage = 1;
              this.getDepartments();//重新刷新页面
            })
            .catch(result=>{//调用后端调用不同
              this.$message({
                message: '系统繁忙，稍后重试',
                type: 'error'
              });
            })
      }).catch(() => {//取消

      });
    },
    getEmployees(){
      this.$http.get("/employee")
          .then(result=>{
            this.employees = result.data;//List<Employee>
          })
    },
    getDeptTree(){
      this.$http.get("/dept/tree").then(result=>{
          console.log(result)
        this.deptTree = result.data;
      })
    }
  },
  mounted() {
    this.getDepartments();
    this.getEmployees();
  }
}

</script>

<style scop/>